<template>
  <el-dialog
    v-model="visible"
    title="更新状态"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="50px">
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="it in statusList"
            :key="it.value"
            :value="it.value"
            :label="it.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :autosize="{ minRows: 5, maxRows: 8 }"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button :loading="submitLoading" type="primary" @click="submitForm"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { updatePaymentStatus } from "@/api/adminPayApi";
import { message } from "@/utils/message";

interface UserForm {
  status: string;
  remark: string;
}
type StatusOption = {
  label: string;
  value: string;
};
defineProps({
  statusList: {
    type: Array as PropType<StatusOption[]>,
    default: () => []
  }
});
const visible = ref(false);

const form = reactive<UserForm>({
  status: "",
  remark: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
};

const userFormRef = ref<FormInstance>();
const submitLoading = ref(false);
const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        await updatePaymentStatus(orderNo.value, form);
        message("更新成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};
const orderNo = ref("");
const open = (order: string) => {
  orderNo.value = order;
  visible.value = true;
};

defineExpose({ open });
</script>
